
const { talentPolicyList } = require('../../../../api/index');
const { isFinished, sliceString } = require('../../../../utils/util');


// pages/home/index.js
Page({
  /*** 页面的初始数据 */
  data: {
    page: {
      titleLike: '',
      pageNumber: 1,
      pageSize: 20
    },
    total: 0, //  总条数
    finished: false,
    loading: false,
    dataList: [],
    list: []
  },
  //  搜索
  async onSearch(event) {
    this.data.page.titleLike = event.detail;
    this.data.page.pageNumber = 1;
    this.data.list = [];
    this.setData({ finished: false }, () => {
      fetchTalentPolicyList.call(this);
    });
  },
  onJump(event) {
    const { id } = event.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageA/pages/active/detail3/index?id=' + id,
    })
  },
  onRefresh() {
    this.data.page.pageNumber = 1;
    this.data.finished = false;
    this.setData({ list: [] }, () => {
      fetchTalentPolicyList.call(this);
    })
  },
  loadMore() {
    fetchTalentPolicyList.call(this);
  },
  /*** 生命周期函数--监听页面加载 */
  onLoad(options) {
    fetchTalentPolicyList.call(this);
  }
})

//  获取 人才补贴列表
async function fetchTalentPolicyList() {
  wx.showLoading({ title: '加载中...' });
  const { errors, result, totalCount } = await talentPolicyList( this.data.page );

  if(errors.lenght > 0) {
    return;
  }

  //  判断数据是不是都已经加载完了
  this.setData({ finished: isFinished(totalCount, this.data.page.pageNumber * this.data.page.pageSize ) }); 
  //  加载更多数据
  this.setData({ list: this.data.list.concat( setResult( result )) });
  this.data.page.pageNumber ++;

  wx.hideLoading();
} 

function setResult( data ) {
  const _data = JSON.parse(JSON.stringify( data ));

  _data.map( item => {
    item.summary = sliceString( item.summary, 22 );
    return item;
  } )
 
  return _data;
}